package com.songlanyun.modules.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.article.dao.ArticleCourseDao;
import com.songlanyun.modules.article.entity.ArticleCourse;
import com.songlanyun.modules.article.service.ArticleCourseService;


@Service("articleCourseService")
public class ArticleCourseServiceImpl extends ServiceImpl<ArticleCourseDao, ArticleCourse> implements ArticleCourseService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ArticleCourse> page = this.page(
                new Query<ArticleCourse>().getPage(params),
                new QueryWrapper<ArticleCourse>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeByAid(Long aid) {
        this.baseMapper.delete(
                new LambdaQueryWrapper<ArticleCourse>()
                        .eq(ArticleCourse::getArticleId, aid)
        );
    }

    @Override
    public void saveArticleCourse(Long aid, Long courseId) {
        ArticleCourse articleCourse = new ArticleCourse();
        articleCourse.setArticleId(aid);
        articleCourse.setCourseId(courseId);
        this.baseMapper.insert(articleCourse);
    }

    @Override
    public void updateArticleCourse(Long aid, Long courseId) {
        ArticleCourse articleCourse = this.baseMapper.selectOne(
                new LambdaQueryWrapper<ArticleCourse>()
                        .eq(ArticleCourse::getArticleId, aid)
                        .last("limit 1")
        );

        if (articleCourse != null) {
            articleCourse.setCourseId(courseId);
            this.baseMapper.updateById(articleCourse);
        } else {
            articleCourse = new ArticleCourse(aid, courseId);
            this.baseMapper.insert(articleCourse);
        }
    }

    @Override
    public Integer articleNum(Long cid) {
        return this.baseMapper.selectCount(
                new LambdaQueryWrapper<ArticleCourse>()
                        .eq(ArticleCourse::getCourseId, cid)
        );
    }

}